package br.com.siscov.control.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import br.com.siscov.control.form.AtendenteForm;
import br.com.siscov.model.funcionario.service.AtendenteService;
import br.com.siscov.model.login.service.LoginService;
import br.com.siscov.model.vo.AtendenteVo;
import br.com.siscov.util.Constantes;

public class CadastrarAtendenteAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ActionErrors errors = new ActionErrors();
		try {

			AtendenteForm atendenteForm = (AtendenteForm) form;

			// dados fake funcionario
			atendenteForm.setCargo("Atendente");
			atendenteForm.setTipo(new Integer(1).toString());

			if (AtendenteService.verificaAtendente(new Integer(atendenteForm.getMatricula()))) {
				if (LoginService.autenticaUsuario(atendenteForm.getLogin(), atendenteForm.getSenha())) {
					AtendenteVo atendenteVo = atendenteForm.populaVO();
					AtendenteService.incluirAtendente(atendenteVo);
					return mapping.findForward(Constantes.FORWARD_SUCESSO);
				}
			}
			errors.add("errors", new ActionMessage("errors.matricula.existente"));
			saveErrors(request, errors);
			return mapping.findForward(Constantes.FWD_ERRO);
		} catch (Exception e) {
			errors.add("errors", new ActionMessage(e.getMessage()));
			saveErrors(request, errors);
			return mapping.findForward(Constantes.FWD_ERRO);
		}
	}
}
